using System;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Text;
using System.Net;
using System.Threading;
using System.Security.Principal;
using System.Windows.Forms;
using PSLib = Microsoft.Office.Project.Server.Library;

namespace DataPopulation
{
    public partial class MainForm : Form
    {
        #region Private Data
        private static Random rnd = new Random(1);
        private int entityLimit = 500;
        private ResultsDlg results = new ResultsDlg();
        private OptionsDlg options = new OptionsDlg();
        private Logging log;
        private Helper helper;

        public delegate void delegateSetStatus(string text, bool verbose);
        #endregion

        #region Form Init
        public MainForm()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            try
            {
                Splash formSplash = new Splash();
                formSplash.Show();
                Application.DoEvents();

                txtNTDomain.Text = Environment.UserDomainName;
                entityLimit = options.EntityLimit;
                txtURL.Text = options.PSUrl;

                helper = new Helper(this);

                formSplash.FadeForm();
                formSplash.Close();

                log = new Logging(options.LoggingEnabled, options.LogPath, options.LogAll);
                log.OpenLogFile();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        #endregion

        #region Helper Methods
        #region UI Helpers
        private void PopulateData()
        {
            wsSecurity.SecurityGroupsDataSet dsGroups = Helper.security.ReadGroupList();
            if (dsGroups == null)
            {
                SetStatus("ReadGroupList failed.", false);
                return;
            }
            foreach (wsSecurity.SecurityGroupsDataSet.SecurityGroupsRow dr in dsGroups.SecurityGroups.Rows)
            {
                lbGroups.Items.Add(dr.WSEC_GRP_NAME);
            }
            lbGroups.SelectedIndex = lbGroups.FindString("Team Member");

            wsSecurity.SecurityCategoriesDataSet dsCategories = Helper.security.ReadCategoryList();
            if (dsCategories == null)
            {
                SetStatus("ReadCategoryList failed.", false);
                return;
            }
            foreach (wsSecurity.SecurityCategoriesDataSet.SecurityCategoriesRow dr in dsCategories.SecurityCategories.Rows)
            {
                lbCategories.Items.Add(dr.WSEC_CAT_NAME);
            }

            WindowsPrincipal wp = new WindowsPrincipal(WindowsIdentity.GetCurrent());
            string domain = wp.Identity.Name;
            int index = domain.IndexOf("\\");
            txtNTDomain.Text = domain.Substring(0, index);

            PopulateProjTypes();
            PopulateCalendar();
            PopulateProjTemplates();
        }

        private void PopulateProjTypes()
        {
            cbProjTypes.Items.Clear();
            foreach (string projectType in Enum.GetNames(typeof(PSLib.Project.ProjectType)))
            {
                cbProjTypes.Items.Add(projectType);
            }
            cbProjTypes.SelectedIndex = cbProjTypes.FindString("Project");
        }

        private void PopulateProjTemplates()
        {
            wsProject.ProjectDataSet dsTemplates = Helper.project.ReadProjectStatus(Guid.Empty, wsProject.DataStoreEnum.WorkingStore,  "", (int)PSLib.Project.ProjectType.Template);
            if (dsTemplates == null)
            {
                SetStatus("ReadProjectStatus failed during PopulateProjTemplates.", false);
                return;
            }

            cbTemplate.DataSource = dsTemplates.Project;
            cbTemplate.DisplayMember = "PROJ_NAME";
            cbTemplate.ValueMember = "PROJ_UID";

            if (dsTemplates.Project.Rows.Count > 0) cbTemplate.SelectedIndex = 0;
        }

        private void PopulateCalendar()
        {
            try
            {
                cbCalTypes.Items.Clear();
                foreach (wsCalendar.CalendarDataSet.CalendarsRow calendarRow in Helper.Calendars.Rows)
                {
                    cbCalTypes.Items.Add(calendarRow.CAL_NAME);
                }
                cbCalTypes.SelectedItem = "Standard";
            }
            catch (Exception ex)
            {
                SetStatus("PopulateCalendar failed. " + ex.Message, false);
            }
        }

        public void SetStatus(string msg, bool verbose)
        {
            if (txtStatus.InvokeRequired)
            {
                delegateSetStatus d = new delegateSetStatus(SetStatus);
                Invoke(d, new object[] { msg, verbose });
            }
            else
            {
                Application.DoEvents();

                txtStatus.Text = msg;
                results.AddMsg(msg);
                if (options.LoggingEnabled)
                {
                    if ((verbose && options.LogAll) || !verbose) log.WriteLog(msg);
                }
            }
        }

        private void SetProjPrefix(string prefix)
        {
            txtProjPrefix.Text = prefix;
            txtTaskPrefix.Text = prefix;
            txtTaskDepsProjPrefix.Text = prefix;
            txtBuildTeamPrefix.Text = prefix;
            txtResProjPrefix.Text = prefix;
            txtPublishProjPrefix.Text = prefix;
        }
        #endregion

        #region Queue Helpers
        private int RetryFailedJobs(int retries)
        {
            int jobsFailed = 0;

            try
            {
                for (int count = 1; count <= retries; count++)
                {
                    DateTime dtCurrent = DateTime.Now;
                    wsQueue.QueueStatusDataSet dsQueue = Helper.queue.ReadAllJobStatusSimple(dtCurrent.AddDays(-1), dtCurrent, 10000, false, wsQueue.SortColumn.JobCompletionState, wsQueue.SortOrder.Ascending);

                    dsQueue.Status.DefaultView.RowFilter = "JobCompletionState = " + (int)PSLib.QueueConstants.JobState.Failed;
                    jobsFailed = dsQueue.Status.DefaultView.Count;
                    foreach (DataRowView rowProject in dsQueue.Status.DefaultView)
                    {
                        Helper.queue.RetryJob((Guid)rowProject["JobGUID"]);
                        SetStatus("Retrying job " + rowProject["JobGUID"] + ".", true);
                    }
                    if (jobsFailed == 0) break;
                }
                return jobsFailed;
            }
            catch (Exception ex)
            {
                SetStatus("Error retrying failed jobs. " + ex.Message, false);
                return jobsFailed;
            }
        }
        #endregion

        #region WorkQueue Helpers
        private CreateResourcesItem AddCreateResourcesItem()
        {
            CreateResourcesItem queueItem = WorkQueues.qCreateResources.NewItem();
            queueItem.resPrefix = txtResNamePrefix.Text;
            queueItem.start = Convert.ToInt32(txtStartNumber.Text);
            queueItem.end = Convert.ToInt32(txtEndNumber.Text);
            queueItem.createCFs = chkUseResCFs.Checked;
            queueItem.leafsOnly = chkResLeafOnly.Checked;
            queueItem.createLogins = chkNTLogin.Checked;
            queueItem.domain = txtNTDomain.Text;
            queueItem.ntAuth = rbNTAuth.Checked;
            queueItem.numDigits = Convert.ToInt32(txtNumOfDigits.Text);
            queueItem.password = txtPassword.Text;
            queueItem.psURL = txtURL.Text;
            queueItem.entityLimit = options.EntityLimit;
            queueItem.connectionString = options.ConnectionString;
            ArrayList itemGroups = new ArrayList();
            itemGroups.Clear();
            foreach (string item in this.lbGroups.SelectedItems)
            {
                itemGroups.Add(item);
            }
            queueItem.securityGroups = itemGroups;
            ArrayList itemCategories = new ArrayList();
            itemCategories.Clear();
            foreach (string item in this.lbCategories.SelectedItems)
            {
                itemCategories.Add(item);
            }
            queueItem.securityCategories = itemCategories;
            WorkQueues.qCreateResources.EnqueueItem(queueItem);
            return queueItem;
        }

        private CreateProjectsItem AddCreateProjectsItem()
        {
            CreateProjectsItem queueItem = WorkQueues.qCreateProjects.NewItem();
            queueItem.calendarType = cbCalTypes.Text;
            queueItem.createCFs = chkUseProjCFs.Checked;
            queueItem.leafsOnly = chkProjLeafOnly.Checked;
            queueItem.ownerEnd = Convert.ToInt32(txtEndingOwner.Text);
            queueItem.ownerNumDigits = Convert.ToInt32(txtNumOwnerDigits.Text);
            queueItem.ownerPrefix = txtOwnerPrefix.Text;
            queueItem.ownerStart = Convert.ToInt32(txtStartingOwner.Text);
            queueItem.projectEnd = Convert.ToInt32(txtProjEndingNumber.Text);
            queueItem.projectNumDigits = Convert.ToInt32(txtNumProjectDigits.Text);
            queueItem.projectPrefix = txtProjPrefix.Text;
            queueItem.projectStart = Convert.ToInt32(txtProjStartingNumber.Text);
            queueItem.projectType = cbProjTypes.Text;
            queueItem.template = (Guid)cbTemplate.SelectedValue;
            queueItem.psURL = txtURL.Text;
            queueItem.entityLimit = options.EntityLimit;
            queueItem.connectionString = options.ConnectionString;
            WorkQueues.qCreateProjects.EnqueueItem(queueItem);
            return queueItem;
        }

        private CreateWinProjItem AddWinProjItem()
        {
            CreateWinProjItem queueItem = WorkQueues.qCreateWinProj.NewItem();
            queueItem.projectPrefix = txtWPProjPrefix.Text;
            queueItem.tasksPerProject = Convert.ToInt32(txtWPNumTasks.Text);
            queueItem.taskPrefix = txtWPTaskPrefix.Text;
            queueItem.numDigits = Convert.ToInt32(txtWPTaskNumDigits.Text);
            queueItem.maxDuration = Convert.ToInt32(txtWPTaskMaxDur.Text);
            queueItem.minDuration = Convert.ToInt32(txtWPTaskMinDur.Text);
            queueItem.maxAssignments = Convert.ToInt32(txtWPMaxAssn.Text);
            queueItem.minAssignments = Convert.ToInt32(txtWPMinAssn.Text);
            queueItem.maxDepDuration = Convert.ToInt32(txtWPDepMaxDur.Text);
            queueItem.minDepDuration = Convert.ToInt32(txtWPDepMinDur.Text);
            queueItem.createTaskCFs = chkWPTaskCFs.Checked;
            queueItem.taskLeafsOnly = chkWPTaskLeafsOnly.Checked;
            queueItem.psURL = txtURL.Text;
            queueItem.entityLimit = options.EntityLimit;
            queueItem.connectionString = options.ConnectionString;
            WorkQueues.qCreateWinProj.EnqueueItem(queueItem);
            return queueItem;
        }

        private CreateTasksItem AddCreateTasksItem()
        {
            CreateTasksItem queueItem = WorkQueues.qCreateTasks.NewItem();
            queueItem.createCFs = chkUseTaskCFs.Checked;
            queueItem.leafsOnly = chkTaskLeafOnly.Checked;
            queueItem.maxDuration = Convert.ToInt32(txtMaxDuration.Text);
            queueItem.minDuration = Convert.ToInt32(txtMinDuration.Text);
            queueItem.numDigits = Convert.ToInt32(txtNumTaskDigits.Text);
            queueItem.projectPrefix = txtTaskProjPrefix.Text;
            queueItem.taskPrefix = txtTaskPrefix.Text;
            queueItem.tasksPerProject = Convert.ToInt32(txtNumTasksPerProj.Text);
            queueItem.psURL = txtURL.Text;
            queueItem.entityLimit = options.EntityLimit;
            queueItem.connectionString = options.ConnectionString;
            WorkQueues.qCreateTasks.EnqueueItem(queueItem);
            return queueItem;
        }

        private CreateCFsItem AddCreateCFsItem()
        {
            CreateCFsItem queueItem = WorkQueues.qCreateCFs.NewItem();
            queueItem.projectPrefix = txtCFProjPrefix.Text;
            queueItem.createProjectCFs = chkCFPopProjects.Checked;
            queueItem.createTaskCFs = chkCFPopTasks.Checked;
            queueItem.createTaskCFs = chkCFPopTasks.Checked;
            queueItem.createTaskCFs = chkCFPopTasks.Checked;
            queueItem.projectLeafsOnly = chkCFProjLeafsOnly.Checked;
            queueItem.taskLeafsOnly = chkCFTaskLeafsOnly.Checked;
            queueItem.resPrefix = txtCFResPrefix.Text;
            queueItem.createResCFs = chkCFPopRes.Checked;
            queueItem.resLeafsOnly = chkCFTaskLeafsOnly.Checked;
            queueItem.psURL = txtURL.Text;
            queueItem.entityLimit = options.EntityLimit;
            queueItem.connectionString = options.ConnectionString;
            WorkQueues.qCreateCFs.EnqueueItem(queueItem);
            return queueItem;
        }

        private CreateDependenciesItem AddCreateDependenciesItem()
        {
            CreateDependenciesItem queueItem = WorkQueues.qCreateDependencies.NewItem();
            queueItem.projectPrefix = txtTaskDepsProjPrefix.Text;
            queueItem.maxDuration = Convert.ToInt32(txtProjMaxDur.Text);
            queueItem.minDuration = Convert.ToInt32(txtProjMinDur.Text);
            queueItem.psURL = txtURL.Text;
            queueItem.entityLimit = options.EntityLimit;
            queueItem.connectionString = options.ConnectionString;
            WorkQueues.qCreateDependencies.EnqueueItem(queueItem);
            return queueItem;
        }

        private BuildTeamItem AddBuildTeamItem()
        {
            BuildTeamItem queueItem = WorkQueues.qBuildTeam.NewItem();
            queueItem.projectPrefix = txtBuildTeamPrefix.Text;
            queueItem.resPrefix = txtBuildTeamResPrefix.Text;
            queueItem.resTeamSize = Convert.ToInt32(txtBuildTeamResSize.Text);
            queueItem.psURL = txtURL.Text;
            queueItem.entityLimit = options.EntityLimit;
            queueItem.connectionString = options.ConnectionString;
            WorkQueues.qBuildTeam.EnqueueItem(queueItem);
            return queueItem;
        }

        private CreateAssignmentsItem AddCreateAssignmentsItem()
        {
            CreateAssignmentsItem queueItem = WorkQueues.qCreateAssignments.NewItem();
            queueItem.maxAssignments = Convert.ToInt32(txtMaxNumAssns.Text);
            queueItem.minAssignments = Convert.ToInt32(txtMinNumAssns.Text);
            queueItem.projectPrefix = txtResProjPrefix.Text;
            queueItem.psURL = txtURL.Text;
            queueItem.entityLimit = options.EntityLimit;
            queueItem.connectionString = options.ConnectionString;
            WorkQueues.qCreateAssignments.EnqueueItem(queueItem);
            return queueItem;
        }

        private PublishProjectsItem AddPublishProjectsItem()
        {
            PublishProjectsItem queueItem = WorkQueues.qPublishProjects.NewItem();
            queueItem.projectPrefix = txtPublishProjPrefix.Text;
            queueItem.psURL = txtURL.Text;
            queueItem.entityLimit = options.EntityLimit;
            queueItem.connectionString = options.ConnectionString;
            WorkQueues.qPublishProjects.EnqueueItem(queueItem);
            return queueItem;
        }
        #endregion
        #endregion

        #region UI Event Handlers
        private void btnLogin_Click(object sender, EventArgs e)
        {
            try
            {
                Cursor = Cursors.WaitCursor;

                if (!txtURL.Text.EndsWith("/")) txtURL.Text = txtURL.Text + "/";
                String baseUrl = txtURL.Text;
                string addUrl = "_vti_bin/psi/";

                Helper.SetWebServiceURLs(baseUrl + addUrl, CredentialCache.DefaultCredentials);

                if (btnLogin.Text == "Logoff")
                {
                    Helper.Logoff();
                    btnLogin.Text = "Login";
                    tcMain.Enabled = false;
                    return;
                }

                if (Helper.Login())
                {
                    Helper.LoadDataCache();
                    SetStatus("Login URL = " + txtURL.Text, false);
                    btnLogin.Text = "Logoff";
                    tcMain.Enabled = true;
                    PopulateData();
                    timerRetry.Enabled = options.EnableRetry;
                }
                else
                {
                    MessageBox.Show("Login failed.");
                    btnLogin.Text = "Login";
                    tcMain.Enabled = false;
                    lbCategories.SelectedIndices.Clear();
                    lbGroups.SelectedIndices.Clear();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                Cursor = Cursors.Default;
            }
        }

        private void btnCreateResources_Click(object sender, EventArgs e)
        {
            try
            {
                // Validate input.
                if (chkNTLogin.Checked)
                {
                    if (txtResNamePrefix.Text.Length == 0) throw new Exception("Resource Name must be entered.");
                    if (txtStartNumber.Text.Length == 0) throw new Exception("Starting Number must be entered.");
                    if (txtEndNumber.Text.Length == 0) throw new Exception("Ending Number must be entered.");
                    if (txtNumOfDigits.Text.Length == 0) throw new Exception("Number of Digits must be entered.");
                    if (chkNTLogin.Checked)
                    {
                        if (txtPassword.Text.Length == 0) throw new Exception("NT password must be entered.");
                    }
                }
                // Add to queue for threaded processing (future)
                if (!results.Visible) results.Visible = true;
                results.Clear();

                btnCreateResources.Enabled = false;

                AddCreateResourcesItem();
                helper.CreateResources();

                btnCreateResources.Enabled = true;
                //SetStatus("Create Resources added to the work queue.", true);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void btnCreateProjects_Click(object sender, EventArgs e)
        {
            // Add to queue for threaded processing (future)
            if (!results.Visible) results.Visible = true;
            results.Clear();

            btnCreateProjects.Enabled = false;

            AddCreateProjectsItem();
            helper.CreateProjects();

            btnCreateProjects.Enabled = true;
            // SetStatus("Create Projects added to the work queue.", true);
        }

        private void btnCreateTasks_Click(object sender, EventArgs e)
        {
            try
            {
                // Add to queue for threaded processing (future)
                if (!results.Visible) results.Visible = true;
                results.Clear();

                btnCreateTasks.Enabled = false;

                AddCreateTasksItem();
                helper.CreateTasks();

                btnCreateTasks.Enabled = true;
                //SetStatus("Create Tasks added to the work queue.", true);
            }
            catch (Exception ex)
            {
                SetStatus(ex.Message, false);
            }
        }


        private void btnWinProj_Click(object sender, EventArgs e)
        {
            try
            {
                // Add to queue for threaded processing (future)
                if (!results.Visible) results.Visible = true;
                results.Clear();

                btnWinProj.Enabled = false;

                AddWinProjItem();
                helper.CreateWinProj();

                btnWinProj.Enabled = true;
                //SetStatus("Create custom fields added to the work queue.", true);
            }
            catch (Exception ex)
            {
                SetStatus(ex.Message, false);
            }
        }

        private void btnAddCFs_Click(object sender, EventArgs e)
        {
            try
            {
                // Add to queue for threaded processing (future)
                if (!results.Visible) results.Visible = true;
                results.Clear();

                btnAddCFs.Enabled = false;

                AddCreateCFsItem();
                helper.CreateCFs();

                btnAddCFs.Enabled = true;
                //SetStatus("Create custom fields added to the work queue.", true);
            }
            catch (Exception ex)
            {
                SetStatus(ex.Message, false);
            }
        }

        private void btnCreateDeps_Click(object sender, EventArgs e)
        {
            try
            {
                // Add to queue for threaded processing (future)
                if (!results.Visible) results.Visible = true;
                results.Clear();

                btnCreateDeps.Enabled = false;

                AddCreateDependenciesItem();
                helper.CreateDeps();

                btnCreateDeps.Enabled = true;
                // SetStatus("Create Dependencies added to the work queue.", true);
            }
            catch (Exception ex)
            {
                SetStatus(ex.Message, false);
            }
        }

        private void btnBuildTeam_Click(object sender, EventArgs e)
        {
            try
            {
                // Add to queue for threaded processing (future)
                if (!results.Visible) results.Visible = true;
                results.Clear();

                btnBuildTeam.Enabled = false;

                AddBuildTeamItem();
                helper.BuildTeam();

                btnBuildTeam.Enabled = true;
                // SetStatus("Build Team added to the work queue.", true);
            }
            catch (Exception ex)
            {
                SetStatus(ex.Message, false);
            }
        }

        private void btnCreateAssns_Click(object sender, EventArgs e)
        {            
            try
            {
                // Add to queue for threaded processing (future)
                if (!results.Visible) results.Visible = true;
                results.Clear();

                btnCreateAssns.Enabled = false;

                AddCreateAssignmentsItem();
                helper.CreateAssns();

                btnCreateAssns.Enabled = true;
                // SetStatus("Create Assignments added to the work queue.", true);
            }
            catch (Exception ex)
            {
                SetStatus(ex.Message, false);
            }
        }

        private void btnPublishProjects_Click(object sender, EventArgs e)
        {
            try
            {
                // Add to queue for threaded processing (future)
                if (!results.Visible) results.Visible = true;
                results.Clear();

                btnPublishProjects.Enabled = false;

                AddPublishProjectsItem();
                helper.PublishProjects();

                btnPublishProjects.Enabled = true;
                // SetStatus("Publish Projects added to the work queue.", true);
            }
            catch (Exception ex)
            {
                SetStatus(ex.Message, false);
            }
        }

        private void chkNTLogin_CheckedChanged(object sender, EventArgs e)
        {
            txtNTDomain.Enabled = chkNTLogin.Checked;
            txtPassword.Enabled = chkNTLogin.Checked;
        }

        private void tcMain_SelectedIndexChanged(object sender, EventArgs e)
        {
        }

        private void txtProjPrefix_Changed(object sender, EventArgs e)
        {
            txtProjPrefix.Text = ((TextBox)sender).Text;
            txtTaskProjPrefix.Text = ((TextBox)sender).Text;
            txtTaskDepsProjPrefix.Text = ((TextBox)sender).Text;
            txtCFProjPrefix.Text = ((TextBox)sender).Text;
            txtBuildTeamPrefix.Text = ((TextBox)sender).Text;
            txtResProjPrefix.Text = ((TextBox)sender).Text;
            txtPublishProjPrefix.Text = ((TextBox)sender).Text;
            txtWPProjPrefix.Text = ((TextBox)sender).Text;
        }

        private void rbNTAuth_CheckedChanged(object sender, EventArgs e)
        {
            grpNTLogin.Enabled = rbNTAuth.Checked;
        }

        private void cbProjTypes_TextChanged(object sender, EventArgs e)
        {
            if (cbProjTypes.Text == "Template")
            {
                gbProjOwner.Enabled = false;
                txtProjMaxDur.Enabled = false;
                txtProjMinDur.Enabled = false;
                chkUseProjCFs.Enabled = false;
                chkProjLeafOnly.Enabled = false;
                gbTasks.Visible = false;
                lblCalendarType.Visible = false;
                cbCalTypes.Visible = false;
                lblTemplate.Visible = true;
                cbTemplate.Visible = true;
            }
            else
            {
                gbProjOwner.Enabled = true;
                txtProjMaxDur.Enabled = true;
                txtProjMinDur.Enabled = true;
                chkUseProjCFs.Enabled = true;
                chkProjLeafOnly.Enabled = true;
                gbTasks.Visible = true;
                lblCalendarType.Visible = true;
                cbCalTypes.Visible = true;
                lblTemplate.Visible = false;
                cbTemplate.Visible = false;
            }
        }

        private void chkUseResCFs_CheckedChanged(object sender, EventArgs e)
        {
            chkResLeafOnly.Enabled = chkUseResCFs.Checked;
        }

        private void chkUseProjCFs_CheckedChanged(object sender, EventArgs e)
        {
            chkProjLeafOnly.Enabled = chkUseProjCFs.Checked;
        }

        private void chkUseTaskCFs_CheckedChanged(object sender, EventArgs e)
        {
            chkTaskLeafOnly.Enabled = chkUseTaskCFs.Checked;
        }

        private void chkCFPopProjects_CheckedChanged(object sender, EventArgs e)
        {
            chkCFProjLeafsOnly.Enabled = chkCFPopProjects.Checked;
        }

        private void chkCFPopTask_CheckedChanged(object sender, EventArgs e)
        {
            chkCFTaskLeafsOnly.Enabled = chkCFPopTasks.Checked;
        }

        private void chkWPTaskCFs_CheckedChanged(object sender, EventArgs e)
        {
            chkWPTaskLeafsOnly.Enabled = chkWPTaskCFs.Checked;
        }

        private void chkCFPopRes_CheckedChanged(object sender, EventArgs e)
        {
            chkCFResLeafsOnly.Enabled = chkCFPopRes.Checked;
        }

        private void menuClose_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void menuOptions_Click(object sender, EventArgs e)
        {
            options.EntityLimit = entityLimit;
            options.LoggingEnabled = log.Enabled;
            options.LogAll = log.LogAll;
            options.LogPath = log.LogFilePath;
            options.PSUrl = txtURL.Text;
            if (options.ShowDialog() == DialogResult.OK)
            {
                entityLimit = options.EntityLimit;
                log.Enabled = options.LoggingEnabled;
                log.LogAll = options.LogAll;
                log.LogFilePath = options.LogPath;
                txtURL.Text = options.PSUrl;
                timerRetry.Enabled = options.EnableRetry;

                log.CloseLogFile();
                log.OpenLogFile();
            }
            options.Hide();
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            options.PSUrl = txtURL.Text;
            options.SaveSettings();
            log.CloseLogFile();
        }

        private void timerRetry_Tick(object sender, EventArgs e)
        {
            int failedJobs = RetryFailedJobs(3);
            if (failedJobs > 0) SetStatus("Retried " + failedJobs.ToString() + " failed jobs.", false);
        }

        private void menuShowResults_Click(object sender, EventArgs e)
        {
            results.Visible = !results.Visible;
        }

        private void menuStatistics_Click(object sender, EventArgs e)
        {
            StatsDlg dlg = new StatsDlg(options.ConnectionString);
            dlg.ShowDialog();
        }

        private void menuCleanup_Click(object sender, EventArgs e)
        {
            CleanupDlg dlg = new CleanupDlg();
            dlg.ShowDialog();
        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            Thread workerThread;
            Helper threadProcs = new Helper(this);

            if (!results.Visible) results.Visible = true;
            results.Clear();

            CreateResourcesItem itemCreateResources = WorkQueues.qCreateResources.PeekItem();
            while (itemCreateResources != null)
            {
                workerThread = new Thread(new ThreadStart(threadProcs.CreateResources));
                workerThread.Start();
                itemCreateResources = WorkQueues.qCreateResources.PeekItem();
            }
            CreateProjectsItem itemCreateProjects = WorkQueues.qCreateProjects.PeekItem();
            while (itemCreateProjects != null)
            {
                workerThread = new Thread(new ThreadStart(threadProcs.CreateProjects));
                workerThread.Start();
                itemCreateProjects = WorkQueues.qCreateProjects.PeekItem();
            }
            CreateTasksItem itemCreateTasks = WorkQueues.qCreateTasks.PeekItem();
            while (itemCreateTasks != null)
            {
                workerThread = new Thread(new ThreadStart(threadProcs.CreateTasks));
                workerThread.Start();
                itemCreateTasks = WorkQueues.qCreateTasks.PeekItem();
            }
            CreateDependenciesItem itemCreateDependencies = WorkQueues.qCreateDependencies.PeekItem();
            while (itemCreateDependencies != null)
            {
                workerThread = new Thread(new ThreadStart(threadProcs.CreateDeps));
                workerThread.Start();
                itemCreateDependencies = WorkQueues.qCreateDependencies.PeekItem();
            }
            BuildTeamItem itemBuildTeam = WorkQueues.qBuildTeam.PeekItem();
            while (itemCreateDependencies != null)
            {
                workerThread = new Thread(new ThreadStart(threadProcs.BuildTeam));
                workerThread.Start();
                itemBuildTeam = WorkQueues.qBuildTeam.PeekItem();
            }
            CreateAssignmentsItem itemCreateAssignments = WorkQueues.qCreateAssignments.PeekItem();
            while (itemCreateAssignments != null)
            {
                workerThread = new Thread(new ThreadStart(threadProcs.CreateAssns));
                workerThread.Start();
                itemCreateAssignments = WorkQueues.qCreateAssignments.PeekItem();
            }
            PublishProjectsItem itemPublishProjects = WorkQueues.qPublishProjects.PeekItem();
            while (itemPublishProjects != null)
            {
                workerThread = new Thread(new ThreadStart(threadProcs.PublishProjects));
                workerThread.Start();
                itemPublishProjects = WorkQueues.qPublishProjects.PeekItem();
            }
        }
        #endregion
    }
}